#include "VideoRecordThread.h"
#include "DeviceTool.h"
#include <QDebug>
#include "FilePicker.h"

void VideoRecordThread::run() {
    const AVInputFormat *fmt = av_find_input_format("avfoundation");
    if (fmt == nullptr) {
        emit this->recordState(VideoRecordFail);
        qDebug() << "打开avfoundation失败";
        return;
    }
    AVFormatContext *ctx = nullptr;
    AVDictionary *options = this->recordOption->optionDict();
    if (avformat_open_input(&ctx, "0", fmt, &options)) {
        emit this->recordState(VideoRecordFail);
        qDebug() << "打开设备失败";
        return;
    }
    QFile file(this->recordPath);
    if (!file.open(QFile::WriteOnly)) {
        emit this->recordState(VideoRecordFail);
        avformat_close_input(&ctx);
        qDebug() << "打开文件失败";
        return;
    }
    DeviceTool::gainDeviceInfo(ctx);
    //  计算每一帧的大小
    AVCodecParameters *params = ctx->streams[0]->codecpar;
    int imageSize = av_image_get_buffer_size((AVPixelFormat)params->format, params->width, params->height, 1);
    AVPacket *pkt = av_packet_alloc();
    int ret = 0;
    emit this->recordState(VideoRecording);
    while (!isInterruptionRequested()) {
        ret = av_read_frame(ctx, pkt);

        if (ret == 0) {
            file.write((const char *)pkt->data, imageSize);
            av_packet_unref(pkt);
        } else if (ret == AVERROR(EAGAIN)) {
            continue;
        } else {
            break;
        }
    }
    /// 释放资源
    av_packet_free(&pkt);
    //  关闭设备
    avformat_close_input(&ctx);
    /// 关闭文件
    file.close();
    emit this->recordState(VideoRecordEnd);
}

VideoRecordThread::~VideoRecordThread() {
    delete recordOption;
    qDebug() << "视频录制停止";
}
